package edu.thu.studio.ormdesigner.editor.action;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.ui.actions.DeleteAction;
import org.eclipse.ui.IWorkbenchPart;

import edu.thu.studio.ormdesigner.editor.ORMGraphicalEditor;
import edu.thu.studio.ormdesigner.editor.command.WithoutUpdateCommand;
import edu.thu.studio.ormdesigner.model.AbstractModel;

public class DeleteWithoutUpdateAction extends DeleteAction {
    private ORMGraphicalEditor editor;
    
    public DeleteWithoutUpdateAction(ORMGraphicalEditor editor) {
        super((IWorkbenchPart) editor);
        this.editor = editor;
        
        this.setActionDefinitionId("org.eclipse.ui.edit.delete");
    }
    
    @Override
    protected boolean calculateEnabled() {
        Command cmd = createDeleteCommand(getSelectedObjects());
        if (cmd == null) {
            return false;
        }
        
        return true;
    }
    
    @SuppressWarnings("rawtypes")
    @Override
    public Command createDeleteCommand(List objects) {
        Command command = super.createDeleteCommand(objects);
        
        if (command == null) {
            return null;
        }
        
        if (command instanceof CompoundCommand) {
            CompoundCommand compoundCommand = (CompoundCommand) command;
            if (compoundCommand.getCommands().isEmpty()) {
                return null;
            }
            
            if (compoundCommand.getCommands().size() == 1) {
                return compoundCommand;
            }
            
            EditPart editPart = this.editor.getGraphicalViewer().getContents();
            AbstractModel diagram = (AbstractModel) editPart.getModel();
            
            return new WithoutUpdateCommand(compoundCommand, diagram, editor);
        }
        
        return command;
    }
    
}
